package com.zzoranor.presentationserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.zzoranor.util.Log;

/**
 * Purpose of Server class is to contain server functionality, 
 * accepting incomming client connections etc. 
 * @author Tim
 *
 */

public class Server {
	
	
	private ServerSocket serverSocket = null;
	private ServerDispatcher serverDispatcher;
	private ClientToServerMessageHandler clientToServerMessageHandler;

	public void startServer(int port) {
		try
		{
			serverSocket = new ServerSocket(port);
			Log.i("Server started on port: " + port);
		}catch(IOException e)
		{
			Log.e("Cannot start server on port: " + port);
			Log.e(e.getMessage());
		}
		
		serverDispatcher = new ServerDispatcher();
		serverDispatcher.start();
		
		Log.i("Server now accepts connections on port: " + port);
		while(true)
		{
			try
			{
				Socket socket = serverSocket.accept();
				ClientInfo clientInfo = new ClientInfo();
				clientToServerMessageHandler = new ClientToServerMessageHandler(serverDispatcher);
				ClientListener clientListener = new ClientListener(clientInfo, serverDispatcher, clientToServerMessageHandler);
				ClientSender clientSender = new ClientSender(clientInfo, serverDispatcher);
				clientInfo.setup(socket, clientListener, clientSender);
				clientListener.setup();
				clientSender.setup();
				
				clientListener.start();
				clientSender.start();
				serverDispatcher.addClient(clientInfo);
	           } catch (IOException e) {
	        	   Log.printStackTrace(e);

	           }
		}
	}

}
